<?php
/**
 * 样例下载管理
 */
require_once (ROOTDIR."common/db_utils.php");
require_once (ROOTDIR."config/sys_config.php");

class DownLogModel
{
    public function __construct()
    {

    }

    public function getDownLog($userId)
    {
        // date_int 整数，如：2018-02-05 对应整数20180205
        $colNames = array('down_cnt', 'date_int');
        $sql = DbUtil::genSelectSql($colNames, "down_log");
        $sql.= " where user_id=?";

        $result = DbUtil::getInstance()->query($sql, $userId);
        if ( count($result) == 0 ) {
            return null;
        }
        $downLog =array();
        $row = $result[0];
        $downLog['down_cnt'] = intval($row['down_cnt']);
        $downLog['date_int'] = intval($row['date_int']);
        return $downLog;
    }

    public function resetDownLog($userId)
    {
        $colNames = array('down_cnt', 'date_int');
        $sql = DbUtil::genUpdateSql($colNames, "down_log");
        $sql .= " where `user_id` = ?";

        // date_int 整数，如：2018-02-05 对应整数20180205
        $dateInt = intval(date('Ymd'));
        $args = array(0, $dateInt, $userId);
        $result = DbUtil::getInstance()->query2($sql, $args);
        return intval($result);
    }

    public function addDownLog($userId) {
        $colNames = array('user_id', 'down_cnt', 'date_int');
        $sql = DbUtil::genInsertSql($colNames, "down_log");

        // date_int 整数，如：2018-02-05 对应整数20180205
        $dateInt = intval(date('Ymd'));
        $args = array($userId, 0, $dateInt);

        $result = DbUtil::getInstance()->query2($sql, $args);
        return intval($result);
    }

    public function incDownCnt($userId)
    {
        $sql = "update `down_log` set `down_cnt`=`down_cnt`+1 where `user_id` = ?";
        $result = DbUtil::getInstance()->query($sql, $userId);
        return intval($result);
    }

    // 验证并获取剩余下载次数
    public function checkAndGetLeftDownCnt($userId)
    {
        // 获取已下载记录
        $downLog = $this->getDownLog($userId);
        $downCnt = 0;
        if ( $downLog == null ) {
            $this->addDownLog($userId);
            $downCnt = 0;
        }
        else {
            $nowDateInt = intval(date('Ymd'));
            $downCnt = $downLog['down_cnt'];
            if ( $nowDateInt != $downLog['date_int'] ) {
                $this->resetDownLog($userId);
                $downCnt = 0;
            }
        }
        return SysConfig::$MAX_DOWN_CNT - $downCnt;
    }
}